//! 运行时抽象层
//! 
//! 定义与具体异步运行时（如Tokio、async-std等）解耦的抽象接口
//! 使得协议层可以在不同运行时间切换而无需修改代码

use std::future::Future;
use std::pin::Pin;
use std::time::Duration;

/// 异步任务句柄抽象
pub trait TaskHandle: Send + 'static {
    /// 取消任务
    fn abort(&self);
    
    /// 检查任务是否完成
    fn is_finished(&self) -> bool;
    
    /// 获取任务ID（用于调试）
    fn task_id(&self) -> String;
}

/// 运行时抽象trait
/// 
/// 核心设计理念：
/// 1. 协议层只依赖这个trait，不知道具体运行时实现
/// 2. 网络层提供具体实现（Tokio、async-std等）
/// 3. 支持任务派发、定时器、通道等核心异步操作
pub trait RuntimeAbstraction: Send + Sync + 'static {
    /// 任务句柄类型
    type Handle: TaskHandle;
    
    /// 派发异步任务
    fn spawn<F>(&self, future: F) -> Self::Handle
    where
        F: Future<Output = ()> + Send + 'static;
    
    /// 休眠指定时间
    fn sleep(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send>>;
    
    /// 创建超时Future
    fn timeout<F, T>(&self, duration: Duration, future: F) -> Pin<Box<dyn Future<Output = Result<T, TimeoutError>> + Send>>
    where
        F: Future<Output = T> + Send + 'static,
        T: Send + 'static;
    
    /// 获取运行时类型标识
    fn runtime_type(&self) -> &'static str;
    
    /// 获取运行时统计信息
    fn stats(&self) -> RuntimeStats;
}

/// 超时错误
#[derive(Debug, Clone)]
pub struct TimeoutError;

impl std::fmt::Display for TimeoutError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Operation timed out")
    }
}

impl std::error::Error for TimeoutError {}

/// 运行时统计信息
#[derive(Debug, Clone)]
pub struct RuntimeStats {
    /// 活跃任务数
    pub active_tasks: u64,
    /// 总派发任务数
    pub total_spawned: u64,
    /// 运行时名称
    pub runtime_name: String,
    /// 是否支持多线程
    pub multi_threaded: bool,
}

impl RuntimeStats {
    pub fn new(runtime_name: String) -> Self {
        Self {
            active_tasks: 0,
            total_spawned: 0,
            runtime_name,
            multi_threaded: true,
        }
    }
}

/// 轻量级运行时接口
/// 
/// 为不需要完整异步功能的场景设计，仅提供基础的任务派发能力
pub trait LightweightRuntime: Send + Sync + 'static {
    /// 派发轻量级任务（可能是协程也可能是线程）
    fn spawn_task<F>(&self, task: F) 
    where
        F: FnOnce() + Send + 'static;
    
    /// 批量派发任务
    fn spawn_batch<F>(&self, tasks: Vec<F>)
    where
        F: FnOnce() + Send + 'static,
    {
        for task in tasks {
            self.spawn_task(task);
        }
    }
    
    /// 获取运行时类型
    fn lightweight_type(&self) -> &'static str;
}

/// 同步运行时实现（使用线程池）
pub struct ThreadPoolRuntime {
    runtime_type: &'static str,
    stats: std::sync::Arc<std::sync::Mutex<RuntimeStats>>,
}

impl ThreadPoolRuntime {
    pub fn new() -> Self {
        Self {
            runtime_type: "ThreadPool",
            stats: std::sync::Arc::new(std::sync::Mutex::new(
                RuntimeStats::new("ThreadPool".to_string())
            )),
        }
    }
}

impl Default for ThreadPoolRuntime {
    fn default() -> Self {
        Self::new()
    }
}

impl LightweightRuntime for ThreadPoolRuntime {
    fn spawn_task<F>(&self, task: F)
    where
        F: FnOnce() + Send + 'static,
    {
        // 使用标准库线程（简单实现，实际可以用线程池）
        std::thread::spawn(task);
        
        // 更新统计
        if let Ok(mut stats) = self.stats.lock() {
            stats.total_spawned += 1;
        }
    }
    
    fn lightweight_type(&self) -> &'static str {
        self.runtime_type
    }
}

